﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Everynet.Models;
using System.Configuration;
using System.Net.Mail;
using Mail.Mailers;
using Mvc.Mailer;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Xml;
using System.Data.Entity;
using System.Data;


namespace Everynet.Controllers
{
    public class AdminController : Controller
    {
        #region[top]
        private IUserMailer _userMailer = new UserMailer();
        //
        // GET: /Welcome/

        public IUserMailer UserMailer
        {
            get { return _userMailer; }
            set { _userMailer = value; }
        }

        //
        // GET: /Admin/
        private EverynetEntities db = new EverynetEntities();
        public ActionResult Index()
        {
             if(Request.IsAuthenticated) 
                    {
                     return RedirectToAction("Dashboard", "Admin");
                    }
                    else
                    {
                  return View();
                      }
           
        }
        #endregion
        #region[Index]
        [HttpPost]
        public ActionResult Index(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
               

                            var adminModel = new AdminModels();
                            var checklogin = from e in db.AdminUsers
                                             where e.UserName == model.UserName
                                                 && e.Password == model.Password
                                             select e;


                            if (checklogin.ToList().Count == 1)
                            {
                                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                                {
                                    return Redirect(returnUrl);
                                }
                                else
                                {
                                    return RedirectToAction("Dashboard", "Admin");
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                            }
                    
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        #endregion
        #region[Dashboard]
        public ActionResult Dashboard()
        {
            var model = new PlanModel();
            model.PlanTypeList = (from e in db.PlanTypes
                                  select e).ToList();
            model.PlanNameList = (from e in db.PlanNames
                                  select e).ToList();
            return View(model);
        }
        #endregion
        #region [LogOff]
        // GET: /Account/LogOff
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Admin");
        }
        #endregion
        #region-------------PlanType-------------
        public ActionResult PlanType()
        {
            var model = new PlanModel();
            model.PlanTypeList = (from e in db.PlanTypes
                                  select e).ToList();

            return View(model);
        }
        [HttpPost]
        public ActionResult PlanType(string searchString)
        {
            var model = new PlanModel();
            model.PlanTypeList = (from e in db.PlanTypes
                                  where e.PlanTypes.Contains(searchString)
                                  select e).ToList();
            return View(model);
        }
        public ActionResult CreateNewPlanType()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateNewPlanType(PlanModel model)
        {
            PlanType plan = new PlanType();
            if (ModelState.IsValid)
            {
                plan.PlanTypes = model.PlanTypes;
                db.AddToPlanTypes(plan);
                db.SaveChanges();
            }
            TempData["message"] = "Plan Type saved successfully";
            return RedirectToAction("PlanType");
        }

        public ActionResult EditPlanType(int id)
        {

            var model = (from e in db.PlanTypes
                         where e.PlanID == id
                         select e).First();

            return View(model);
        }

        [HttpPost]
        public ActionResult EditPlanType(PlanType model)
        {
            var plan = (from e in db.PlanTypes
                        where e.PlanID == model.PlanID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.PlanTypes.Attach(db.PlanTypes.Single(c => c.PlanID == model.PlanID));
                db.PlanTypes.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "Plan Type updated successfully";
            return RedirectToAction("PlanType");
        }
        public ActionResult DeletePlanType(int id)
        {
            var model = (from e in db.PlanTypes
                         where e.PlanID == id
                         select e).First();
            db.PlanTypes.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "Plan Type Deleted successfully";
            return RedirectToAction("PlanType");
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
        #region-------------PlanName-------------
        public ActionResult PlanName()
        {

            var model = new PlanModel();
            model.PlanNameList = (from e in db.PlanNames
                                  select e).ToList();

            return View(model);
        }
        [HttpPost]
        public ActionResult PlanName(string searchString)
        {
            var model = new PlanModel();
            model.PlanNameList = (from e in db.PlanNames
                                  where e.Name.Contains(searchString)
                                  select e).ToList();
            return View(model);
        }
        public ActionResult CreateNewPlanName()
        {
            var model = from d in db.PlanTypes
                        orderby d.PlanTypes
                        select d;

            ViewBag.PlanTypes = new SelectList(model, "PlanID", "PlanTypes");
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateNewPlanName(PlanModel model)
        {
            PlanName plan = new PlanName();
            if (ModelState.IsValid)
            {
                plan.Name = model.Name;
                plan.PlanID = Convert.ToInt32(model.PlanTypes);
                plan.Agreement = model.Agreement.Replace("<ul>", "<ul class='agree'>");
                plan.RedirectUrl = model.RedirectUrl;
                db.AddToPlanNames(plan);
                db.SaveChanges();
            }
            TempData["message"] = "Plan Name saved successfully";
            return RedirectToAction("PlanName");
        }
        public ActionResult EditPlanName(int id)
        {
            var model = new PlanName();
            model = (from e in db.PlanNames
                     where e.ID == id
                     select e).First();

            var mod = from d in db.PlanTypes
                      orderby d.PlanTypes
                      select d;
            ViewBag.PlanID = new SelectList(mod, "PlanID", "PlanTypes", model.PlanID);
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditPlanName(PlanName model)
        {
            var plan = (from e in db.PlanNames
                        where e.ID == model.ID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.PlanNames.Attach(db.PlanNames.Single(c => c.ID == model.ID));
                db.PlanNames.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "Plan updated successfully";
            return RedirectToAction("PlanName");
        }
        public ActionResult DeletePlanName(int id)
        {
            var model = (from e in db.PlanNames
                         where e.ID == id
                         select e).First();
            db.PlanNames.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "Plan Name Deleted successfully";
            return RedirectToAction("PlanName");
        }
        #endregion
        #region-------------PlanNameDetail-------------
        public ActionResult PlanNamesDetail()
        {
            var returnList = db.PlanNamesDetails.ToList();
            return View(returnList);
        }
        [HttpPost]
        public ActionResult PlanNamesDetail(string searchString)
        {


            var model = from e in db.PlanNamesDetails
                        where e.PlanDetailName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreatePlanNamesDetail()
        {
            var model = from d in db.PlanNames
                        orderby d.Name
                        select d;

            ViewBag.PlanNamesID = new SelectList(model, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult CreatePlanNamesDetail(PlanNamesDetail model)
        {
            PlanNamesDetail plan = new PlanNamesDetail();
            if (ModelState.IsValid)
            {
                plan.PlanDetailName = model.PlanDetailName;
                plan.PlanDetailQuota = model.PlanDetailQuota;
                plan.Price = model.Price;
                plan.PlanNamesID = model.PlanNamesID;
                db.AddToPlanNamesDetails(plan);
                db.SaveChanges();
               
            }
            TempData["message"] = "Plan Name Detail saved successfully";
            return RedirectToAction("PlanNamesDetail");
        }
        public ActionResult EditPlanNamesDetail(int id)
        {
            var model = new PlanNamesDetail();
            model = (from e in db.PlanNamesDetails
                     where e.PlanNamesDetailID == id
                     select e).First();

            var mod = from d in db.PlanNames
                      orderby d.Name
                      select d;
            ViewBag.PlanNamesID = new SelectList(mod, "ID", "Name", model.PlanNamesID);
            return View(model);
        }
        [HttpPost]
        public ActionResult EditPlanNamesDetail(PlanNamesDetail model)
        {
            var plan = (from e in db.PlanNamesDetails
                        where e.PlanNamesDetailID == model.PlanNamesDetailID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.PlanNamesDetails.Attach(db.PlanNamesDetails.Single(c => c.PlanNamesDetailID == model.PlanNamesDetailID));
                db.PlanNamesDetails.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "Plan Detail updated successfully";
            return RedirectToAction("PlanNamesDetail");
        }
        public ActionResult DeletePlanNamesDetail(int id)
        {
            var model = (from e in db.PlanNamesDetails
                         where e.PlanNamesDetailID == id
                         select e).First();
            db.PlanNamesDetails.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "Plan Name Detail Deleted successfully";
            return RedirectToAction("PlanNamesDetail");
        }
        #endregion
        #region-------------Extra-------------
        public ActionResult Extra()
        {
            return View(db.Extras.ToList());
        }
        [HttpPost]
        public ActionResult Extra(string searchString)
        {

            var model = from e in db.Extras
                        where e.ExtrasName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreateExtra()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreateExtra(Extra model)
        {

            if (ModelState.IsValid)
            {
                db.AddToExtras(model);
                db.SaveChanges();
            }
            TempData["message"] = "Extra saved successfully";
            return RedirectToAction("Extra");
        }
        public ActionResult EditExtra(int id)
        {
            var model = new Extra();
            model = (from e in db.Extras
                     where e.ExtrasID == id
                     select e).First();
            return View(model);
        }
        [HttpPost]
        public ActionResult EditExtra(Extra model)
        {
            var plan = (from e in db.Extras
                        where e.ExtrasID == model.ExtrasID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.Extras.Attach(db.Extras.Single(c => c.ExtrasID == model.ExtrasID));
                db.Extras.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "Extra updated successfully";
            return RedirectToAction("Extra");
        }
        public ActionResult DeleteExtra(int id)
        {
            var model = (from e in db.Extras
                         where e.ExtrasID == id
                         select e).First();
            db.Extras.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "Extra Deleted successfully";
            return RedirectToAction("Extra");
        }
        #endregion

        #region-------------Hardwares-------------
        public ActionResult Hardware()
        {
            return View(db.Hardwares.ToList());
        }
        [HttpPost]
        public ActionResult Hardware(string searchString)
        {
           var model = from e in db.Hardwares
                        where e.HardwareName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreateHardware()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreateHardware(Hardware model)
        {

            if (ModelState.IsValid)
            {
                db.AddToHardwares(model);
                db.SaveChanges();
            }
            TempData["message"] = "Hardware saved successfully";
            return RedirectToAction("Hardware");
        }
        public ActionResult EditHardware(int id)
        {
            var model = new Hardware();
            model = (from e in db.Hardwares
                     where e.HardwareID == id
                     select e).First();
            return View(model);
        }
        [HttpPost]
        public ActionResult EditHardware(Hardware model)
        {
            var plan = (from e in db.Hardwares
                        where e.HardwareID == model.HardwareID
                        select e).First();
            if (ModelState.IsValid)
            {
                db.Hardwares.Attach(db.Hardwares.Single(c => c.HardwareID == model.HardwareID));
                db.Hardwares.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "Hardware updated successfully";
            return RedirectToAction("Hardware");
        }
        public ActionResult DeleteHardware(int id)
        {
            var model = (from e in db.Hardwares
                         where e.HardwareID == id
                         select e).First();
            db.Hardwares.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "Hardware Deleted successfully";
            return RedirectToAction("Hardware");
        }
        #endregion

        #region-------------subHardware-------------
        public ActionResult subHardware()
        {
            return View(db.SubHardwares.ToList());
        }
        [HttpPost]
        public ActionResult subHardware(string searchString)
        {

            var model = from e in db.SubHardwares
                        where e.SubHardwareName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreatesubHardware()
        {
            var model = from d in db.Hardwares
                        orderby d.HardwareName
                        select d;

            ViewBag.HardwareID = new SelectList(model, "HardwareID", "HardwareName");
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreatesubHardware(SubHardware model)
        {
            if (ModelState.IsValid)
            {
                model.Agreement = model.Agreement.Replace("<ul>", "<ul class='agree'>");
                db.AddToSubHardwares(model);
                db.SaveChanges();
            }
            TempData["message"] = "subHardware saved successfully";
            return RedirectToAction("subHardware");
        }
        public ActionResult EditSubHardware(int id)
        {
            var model = new SubHardware();
            model = (from e in db.SubHardwares
                     where e.SubHardwareID== id
                     select e).First();

            var mod = from d in db.Hardwares
                      orderby d.HardwareName
                      select d;
            ViewBag.HardwareID = new SelectList(mod, "HardwareID", "HardwareName", model.HardwareID);
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditSubHardware(SubHardware model)
        {
            var plan = (from e in db.SubHardwares
                        where e.SubHardwareID == model.SubHardwareID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.SubHardwares.Attach(db.SubHardwares.Single(c => c.SubHardwareID == model.SubHardwareID));
                db.SubHardwares.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "subHardware updated successfully";
            return RedirectToAction("subHardware");
        }
        public ActionResult DeletesubHardware(int id)
        {
            var model = (from e in db.SubHardwares
                         where e.SubHardwareID == id
                         select e).First();
            db.SubHardwares.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "subHardware Deleted successfully";
            return RedirectToAction("subHardware");
        }
        #endregion

        #region-------------SubHardwareDetails-------------
        public ActionResult SubHardwareDetails()
        {
            return View(db.SubHardwaresDetails.ToList());
        }
        [HttpPost]
        public ActionResult SubHardwareDetails(string searchString)
        {

            var model = from e in db.SubHardwaresDetails
                        where e.SubHardwareDetailName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreateSubHardwareDetails()
        {
            var model = from d in db.SubHardwares
                        orderby d.SubHardwareName
                        select d;

            ViewBag.SubHardwareID = new SelectList(model, "SubHardwareID", "SubHardwareName");
            return View();
        }
        [HttpPost]
        public ActionResult CreateSubHardwareDetails(SubHardwaresDetail model)
        {

            if (ModelState.IsValid)
            {
                db.AddToSubHardwaresDetails(model);
                db.SaveChanges();

            }
            TempData["message"] = "SubHardwareDetails saved successfully";
            return RedirectToAction("SubHardwareDetails");
        }
        public ActionResult EditSubHardwareDetails(int id)
        {
            var model = new SubHardwaresDetail();
            model = (from e in db.SubHardwaresDetails
                     where e.SubHardwareDetailID == id
                     select e).First();
            var mod = from d in db.SubHardwares
                      orderby d.SubHardwareName
                      select d;
            ViewBag.SubHardwareID = new SelectList(mod, "SubHardwareID", "SubHardwareName", model.SubHardwareID);
            return View(model);
        }
        [HttpPost]
        public ActionResult EditSubHardwareDetails(SubHardwaresDetail model)
        {
            var plan = (from e in db.SubHardwaresDetails
                        where e.SubHardwareDetailID == model.SubHardwareDetailID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.SubHardwaresDetails.Attach(db.SubHardwaresDetails.Single(c => c.SubHardwareDetailID == model.SubHardwareDetailID));
                db.SubHardwaresDetails.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "SubHardwareDetails updated successfully";
            return RedirectToAction("SubHardwareDetails");
        }
        public ActionResult DeleteSubHardwareDetails(int id)
        {
            var model = (from e in db.SubHardwaresDetails
                         select e).First();
            db.SubHardwaresDetails.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "SubHardwareDetails Deleted successfully";
            return RedirectToAction("SubHardwareDetails");
        }
        #endregion

        #region-------------subExtra-------------
        public ActionResult subExtra()
        {
            return View(db.SubExtras.ToList());
        }
        [HttpPost]
        public ActionResult subExtra(string searchString)
        {

            var model = from e in db.SubExtras
                        where e.SubExtrasName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreatesubExtra()
        {
            var model = from d in db.Extras
                        orderby d.ExtrasName
                        select d;

            ViewBag.ExtrasID = new SelectList(model, "ExtrasID", "ExtrasName");
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreatesubExtra(SubExtra model)
        {

            if (ModelState.IsValid)
            {
                model.Agreement = model.Agreement.Replace("<ul>", "<ul class='agree'>");
                db.AddToSubExtras(model);
                db.SaveChanges();
            }
            TempData["message"] = "subExtra saved successfully";
            return RedirectToAction("subExtra");
        }
        public ActionResult EditSubExtras(int id)
        {
            var model = new SubExtra();
            model = (from e in db.SubExtras
                     where e.SubExtrasID == id
                     select e).First();

            var mod = from d in db.Extras
                      orderby d.ExtrasName
                      select d;
            ViewBag.ExtrasID = new SelectList(mod, "ExtrasID", "ExtrasName", model.ExtrasID);
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditSubExtras(SubExtra model)
        {
            var plan = (from e in db.SubExtras
                        where e.SubExtrasID == model.SubExtrasID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.SubExtras.Attach(db.SubExtras.Single(c => c.SubExtrasID == model.SubExtrasID));
                db.SubExtras.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "subExtra updated successfully";
            return RedirectToAction("subExtra");
        }
        public ActionResult DeletesubExtra(int id)
        {
            var model = (from e in db.SubExtras
                         where e.SubExtrasID == id
                         select e).First();
            db.SubExtras.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "subExtra Deleted successfully";
            return RedirectToAction("subExtra");
        }
        #endregion
       
        #region-------------ExtraPlanQuota-------------
        public ActionResult ExtraPlanQuota()
        {
            return View(db.ExtraPlanQuotas.ToList());
        }

        public ActionResult CreateExtraPlanQuota()
        {
            var model = from d in db.SubExtras
                        orderby d.SubExtrasName
                        select d;

            ViewBag.SubExtrasID = new SelectList(model, "SubExtrasID", "SubExtrasName");
            return View();
        }
        [HttpPost]
        public ActionResult CreateExtraPlanQuota(ExtraPlanQuota model)
        {

            if (ModelState.IsValid)
            {
                db.AddToExtraPlanQuotas(model);
                db.SaveChanges();
            }
            TempData["message"] = "ExtraPlanQuota saved successfully";
            return RedirectToAction("ExtraPlanQuota");
        }
        public ActionResult EditExtraPlanQuota(int id)
        {
            var model = new ExtraPlanQuota();
            model = (from e in db.ExtraPlanQuotas
                     where e.ExtraPlanQuotaID == id
                     select e).First();

            var mod = from d in db.SubExtras
                      orderby d.SubExtrasName
                      select d;
            ViewBag.SubExtrasID = new SelectList(mod, "SubExtrasID", "SubExtrasName", model.SubExtrasID);
            return View(model);
        }
        [HttpPost]
        public ActionResult EditExtraPlanQuota(ExtraPlanQuota model)
        {
            var plan = (from e in db.ExtraPlanQuotas
                        where e.ExtraPlanQuotaID == model.ExtraPlanQuotaID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.ExtraPlanQuotas.Attach(db.ExtraPlanQuotas.Single(c => c.ExtraPlanQuotaID == model.ExtraPlanQuotaID));
                db.ExtraPlanQuotas.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "ExtraPlanQuota updated successfully";
            return RedirectToAction("ExtraPlanQuota");
        }
        public ActionResult DeleteExtraPlanQuota(int id)
        {
            var model = (from e in db.ExtraPlanQuotas
                         where e.ExtraPlanQuotaID == id
                         select e).First();
            db.ExtraPlanQuotas.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "ExtraPlanQuota Deleted successfully";
            return RedirectToAction("ExtraPlanQuota");
        }
        #endregion
        #region-------------PlanQuota-------------
        public ActionResult PlanQuota()
        {
            return View(db.PlanQuotas.ToList());
        }
        public ActionResult CreatePlanQuota()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreatePlanQuota(PlanQuota model)
        {

            if (ModelState.IsValid)
            {
                db.AddToPlanQuotas(model);
                db.SaveChanges();
            }
            TempData["message"] = "PlanQuota saved successfully";
            return RedirectToAction("PlanQuota");
        }
        public ActionResult EditPlanQuota(int id)
        {
            var model = new PlanQuota();
            model = (from e in db.PlanQuotas
                     where e.PlanQuotaID == id
                     select e).First();


            var mod = from d in db.PlanNames
                      orderby d.Name
                      select d;
            ViewBag.PlannamesID = new SelectList(mod, "ID", "Name", model.PlanNamesID);

            return View(model);


          

       }
        [HttpPost]
        public ActionResult EditPlanQuota(PlanQuota model)
        {
            var plan = (from e in db.PlanQuotas
                        where e.PlanQuotaID == model.PlanQuotaID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.PlanQuotas.Attach(db.PlanQuotas.Single(c => c.PlanQuotaID == model.PlanQuotaID));
                db.PlanQuotas.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "PlanQuota updated successfully";
            return RedirectToAction("PlanQuota");
       }
        public ActionResult DeletePlanQuota(int id)
        {
            var model = (from e in db.PlanQuotas
                         where e.PlanQuotaID == id
                         select e).First();
            db.PlanQuotas.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "PlanQuota Deleted successfully";
            return RedirectToAction("PlanQuota");
        }
        #endregion
       
        #region-------------SubExtrasDetails-------------
        public ActionResult SubExtrasDetails()
        {
            return View(db.SubExtrasDetails.ToList());
        }
        [HttpPost]
        public ActionResult SubExtrasDetails(string searchString)
        {

            var model = from e in db.SubExtrasDetails
                        where e.SubExtrasDetailName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreateSubExtrasDetails()
        {
            var model = from d in db.SubExtras
                        orderby d.SubExtrasName
                        select d;

            ViewBag.SubExtrasID = new SelectList(model, "SubExtrasID", "SubExtrasName");
            return View();
        }
        [HttpPost]
        public ActionResult CreateSubExtrasDetails(SubExtrasDetail model)
        {

            if (ModelState.IsValid)
            {
                db.AddToSubExtrasDetails(model);
                db.SaveChanges();
                
            }
            TempData["message"] = "SubExtrasDetails saved successfully";
            return RedirectToAction("SubExtrasDetails");
        }
        public ActionResult EditSubExtrasDetails(int id)
        {
            var model = new SubExtrasDetail();
            model = (from e in db.SubExtrasDetails
                     where e.SubExtrasDetailID == id
                     select e).First();
            var mod = from d in db.SubExtras
                      orderby d.SubExtrasName
                      select d;
            ViewBag.SubExtrasID = new SelectList(mod, "SubExtrasID", "SubExtrasName", model.SubExtrasID);
            return View(model);
        }
        [HttpPost]
        public ActionResult EditSubExtrasDetails(SubExtrasDetail model)
        {
            var plan = (from e in db.SubExtrasDetails
                        where e.SubExtrasDetailID == model.SubExtrasDetailID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.SubExtrasDetails.Attach(db.SubExtrasDetails.Single(c => c.SubExtrasDetailID == model.SubExtrasDetailID));
                db.SubExtrasDetails.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "SubExtrasDetails updated successfully";
            return RedirectToAction("SubExtrasDetails");
        }
        public ActionResult DeleteSubExtrasDetails(int id)
        {
            var model = (from e in db.SubExtrasDetails
                         where e.SubExtrasDetailID == id
                         select e).First();
            db.SubExtrasDetails.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "SubExtrasDetails Deleted successfully";
            return RedirectToAction("SubExtrasDetails");
        }
        #endregion
       
        #region-------------AdslProvider-------------
        public ActionResult AdslProvider()
        {
            return View(db.AdslProviders.ToList());
        }
        [HttpPost]
        public ActionResult AdslProvider(string searchString)
        {


            var model = from e in db.AdslProviders
                        where e.ADSLName.Contains(searchString)
                        select e;

            return View(model);
        }
        public ActionResult CreateAdslProvider()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreateAdslProvider(ADSLProvider model)
        {
            AdslProvider plan = new AdslProvider();
            if (ModelState.IsValid)
            {
                plan.ADSLName = model.ADSLName;
                db.AddToAdslProviders(plan);
                db.SaveChanges();
            }
            TempData["message"] = "AdslProvider saved successfully";
            return RedirectToAction("AdslProvider");
        }
        public ActionResult EditAdslProvider(int id)
        {
            var model = new AdslProvider();
            model = (from e in db.AdslProviders
                     where e.ADSLProviderID == id
                     select e).First();

            return View(model);
        }
        [HttpPost]
        public ActionResult EditAdslProvider(AdslProvider model)
        {
            var plan = (from e in db.AdslProviders
                        where e.ADSLProviderID == model.ADSLProviderID
                        select e).First();
            if (ModelState.IsValid)
            {

                db.AdslProviders.Attach(db.AdslProviders.Single(c => c.ADSLProviderID == model.ADSLProviderID));
                db.AdslProviders.ApplyCurrentValues(model);
                db.SaveChanges();
            }
            TempData["message"] = "AdslProvider updated successfully";
            return RedirectToAction("AdslProvider");
        }
        public ActionResult DeleteAdslProvider(int id)
        {
            var model = (from e in db.AdslProviders
                         where e.ADSLProviderID == id
                         select e).First();
            db.AdslProviders.DeleteObject(model);
            db.SaveChanges();
            TempData["message"] = "AdslProvider Deleted successfully";
            return RedirectToAction("AdslProvider");
        }
        #endregion
        #region [Registered Users]
        public ActionResult RegisteredUsers(string searchString)
        {
            var model = new signUpModel();

            if (string.IsNullOrEmpty(searchString))
            {
                model.listSignUpDetail = (from U in db.Users
                                          join UT in db.UserTypes on U.UserTypeID equals UT.UserTypeID
                                          join AP in db.AdslProviders on new { ADSLProviderID = (Int32)U.ADSLprovider } equals new { ADSLProviderID = AP.ADSLProviderID } into AP_join
                                          from AP in AP_join.DefaultIfEmpty()
                                          join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID } into PND_join
                                          from PND in PND_join.DefaultIfEmpty()
                                          join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID } into PQ_join
                                          from PQ in PQ_join.DefaultIfEmpty()
                                          orderby U.ID descending
                                          select new signUpModel()
                                         {
                                             ID = U.ID,
                                             Title = U.Title,
                                             FirstName = U.FirstName,
                                             LastName = U.LastName,
                                             MobileNumber = U.MobileNumber,
                                             Email = U.Email,
                                             ADSLName = AP.ADSLName,
                                             ServiceAddress = U.ServiceAddress,
                                             ServicePhoneNumber = U.ServicePhoneNumber,
                                             UserName = U.UserName,
                                             ADSLprovider = (Int32?)U.ADSLprovider,
                                             PlanNamesDetailID = (Int32?)U.PlanNamesDetailID,
                                             PlanQuotaID = (Int32?)U.PlanQuotaID,
                                             ADSLproviderOther = U.ADSLproviderOther,
                                             TypeName = UT.TypeName,
                                             PlanDetailName = PND.PlanDetailName,
                                             PlanQuotaValue = (Int32?)PQ.PlanQuotaValue,
                                             PlanQuotaInterval = PQ.PlanQuotaInterval,
                                             RegisterDateTime = U.RegisterDateTime,
                                             IPAddress = U.IPAddress
                                         }).ToList();
            }
            else
            {

                model.listSignUpDetail = (from U in db.Users
                                          join UT in db.UserTypes on U.UserTypeID equals UT.UserTypeID
                                          join AP in db.AdslProviders on new { ADSLProviderID = (Int32)U.ADSLprovider } equals new { ADSLProviderID = AP.ADSLProviderID } into AP_join
                                          from AP in AP_join.DefaultIfEmpty()
                                          join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID } into PND_join
                                          from PND in PND_join.DefaultIfEmpty()
                                          join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID } into PQ_join
                                          from PQ in PQ_join.DefaultIfEmpty()
                                          where (U.FirstName.Contains(searchString) || U.LastName.Contains(searchString))
                                          orderby U.ID descending
                                          select new signUpModel()
                                          {
                                              ID = U.ID,
                                              Title = U.Title,
                                              FirstName = U.FirstName,
                                              LastName = U.LastName,
                                              MobileNumber = U.MobileNumber,
                                              Email = U.Email,
                                              ADSLName = AP.ADSLName,
                                              ServiceAddress = U.ServiceAddress,
                                              ServicePhoneNumber = U.ServicePhoneNumber,
                                              UserName = U.UserName,
                                              ADSLprovider = (Int32?)U.ADSLprovider,
                                              PlanNamesDetailID = (Int32?)U.PlanNamesDetailID,
                                              PlanQuotaID = (Int32?)U.PlanQuotaID,
                                              ADSLproviderOther = U.ADSLproviderOther,
                                              TypeName = UT.TypeName,
                                              PlanDetailName = PND.PlanDetailName,
                                              PlanQuotaValue = (Int32?)PQ.PlanQuotaValue,
                                              PlanQuotaInterval = PQ.PlanQuotaInterval,
                                              RegisterDateTime = U.RegisterDateTime,
                                              IPAddress = U.IPAddress
                                          }).ToList();
            }
            return View("RegisteredUsers", model);
        }

        public ActionResult DetailUsers(Int64 id)
        {
            var model = new signUpModel();
            model.listSignUpDetail = (from U in db.Users
                                      join UT in db.UserTypes on U.UserTypeID equals UT.UserTypeID
                                      join AP in db.AdslProviders on new { ADSLProviderID = (Int32)U.ADSLprovider } equals new { ADSLProviderID = AP.ADSLProviderID } into AP_join
                                      from AP in AP_join.DefaultIfEmpty()
                                      join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID } into PND_join
                                      from PND in PND_join.DefaultIfEmpty()
                                      join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID } into PQ_join
                                      from PQ in PQ_join.DefaultIfEmpty()
                                      where U.ID == id
                                      orderby U.ID descending
                                      select new signUpModel()
                                      {
                                          ID = U.ID,
                                          Title = U.Title,
                                          FirstName = U.FirstName,
                                          LastName = U.LastName,
                                          MobileNumber = U.MobileNumber,
                                          Email = U.Email,
                                          ADSLName = AP.ADSLName,
                                          ServiceAddress = U.ServiceAddress,
                                          ServicePhoneNumber = U.ServicePhoneNumber,
                                          UserName = U.UserName,
                                          ADSLprovider = (Int32?)U.ADSLprovider,
                                          PlanNamesDetailID = (Int32?)U.PlanNamesDetailID,
                                          PlanQuotaID = (Int32?)U.PlanQuotaID,
                                          ADSLproviderOther = U.ADSLproviderOther,
                                          TypeName = UT.TypeName,
                                          PlanDetailName = PND.PlanDetailName,
                                          PlanQuotaValue = (Int32?)PQ.PlanQuotaValue,
                                          PlanQuotaInterval = PQ.PlanQuotaInterval,
                                          RegisterDateTime = U.RegisterDateTime,
                                          IPAddress = U.IPAddress
                                      }).ToList();

            return View("DetailUsers", model);
        }
        #endregion
        #region [Orders]
        public ActionResult Orders(string searchString)
        {
            var model = new OrdersModel();
            List<OrdersModel> lstmodel = new List<OrdersModel>();

            if (string.IsNullOrEmpty(searchString))
            {
                var result = db.GetTotalPrice().ToList();

                foreach (var getresult in result)
                {
                    OrdersModel modellist = new OrdersModel();
                    modellist.ID = getresult.ID;
                    modellist.FirstName = getresult.FirstName;
                    modellist.LastName = getresult.LastName;
                    modellist.OrderStatus = getresult.OrderStatus;
                    modellist.TotalCost = getresult.TotalCost;
                    modellist.IPAddress = getresult.IPAddress;
                    modellist.RegisterDateTime = getresult.RegisterDateTime;
                    lstmodel.Add(modellist);
                }
                model.listOrders = lstmodel;
            }
            else
            {
                var result = db.GetTotalPriceByName(searchString).ToList();

                foreach (var getresult in result)
                {
                    OrdersModel modellist = new OrdersModel();
                    modellist.ID = getresult.ID;
                    modellist.FirstName = getresult.FirstName;
                    modellist.LastName = getresult.LastName;
                    modellist.OrderStatus = getresult.OrderStatus;
                    modellist.TotalCost = getresult.TotalCost;
                    modellist.IPAddress = getresult.IPAddress;
                    modellist.RegisterDateTime = getresult.RegisterDateTime;
                    lstmodel.Add(modellist);
                }
                model.listOrders = lstmodel;

                
            }
            return View("Orders", model);
        }

        public ActionResult EditOrders(Int64 id)
        {
            var model = new OrdersModel();
            model.OrderStatus = (from e in db.Orders
                                 where e.UserID == id
                                 select e.OrderStatus).FirstOrDefault();
            model.SelectedOrderStatus = getOrderStatus();
            return View("EditOrders", model);
        }

        [HttpPost]
        public ActionResult EditOrders(OrdersModel model)
        {

            //Check if UserId in Order table if Exists Update that otherwise Insert Value
            var checkValue = (from e in db.Orders
                              where e.UserID == model.ID
                              select e.OrderID).SingleOrDefault();

            //if checkvalue zero means no entry in table, insert the row

            if (checkValue == 0) //insert
            {
                Order modelOrder = new Order() { UserID = model.ID, OrderStatus = (Int32)model.OrderStatus };
                db.AddToOrders(modelOrder);
                db.SaveChanges();

                SendMailAfterorderStatusChange(model.OrderStatus, model.ID);
            }
            else //update
            {
                var result = (from e in db.Orders
                              where e.UserID == model.ID
                              select e).SingleOrDefault();
                if (TryUpdateModel(result, new[] { "OrderStatus" }))
                {
                    db.SaveChanges();
                    SendMailAfterorderStatusChange(model.OrderStatus, model.ID);
                }
            }




            return RedirectToAction("Orders");
        }
        public ActionResult DetailOrders(Int64 id)
        {

            var model = (from U in db.Users
                         join PQ in db.PlanQuotas on new { PlanQuotaID = (Int32)U.PlanQuotaID } equals new { PlanQuotaID = PQ.PlanQuotaID }
                         join PND in db.PlanNamesDetails on new { PlanNamesDetailID = (Int32)U.PlanNamesDetailID } equals new { PlanNamesDetailID = PND.PlanNamesDetailID }
                         join PN in db.PlanNames on new { ID = PND.PlanNamesID } equals new { ID = PN.ID }
                         where
                           U.ID == id
                         select new SummaryModel()
                         {
                             ID = id,
                             Name = PN.Name,
                             ServicePhoneNumber = U.ServicePhoneNumber,
                             PlanDetailName = PND.PlanDetailName,
                             PlanQuotaValue = PQ.PlanQuotaValue,
                             PlanQuotaInterval = PQ.PlanQuotaInterval,
                             SetupCost = PQ.SetupCost,
                             Price = PND.Price,
                             TotalCost = (System.Decimal?)((PND.Price * PQ.PlanQuotaValue) + PQ.SetupCost)
                         }).SingleOrDefault();

            if (model != null)
            {
                model.listSummaryModel = from SEDA in db.SubExtrasDetailAssignToUsers
                                         join SED in db.SubExtrasDetails on SEDA.SubExtrasDetailID equals SED.SubExtrasDetailID
                                         join SE in db.SubExtras on new { SubExtrasID = (Int32)SED.SubExtrasID } equals new { SubExtrasID = SE.SubExtrasID }
                                         join EPQU in db.ExtraPlanQuotaAssigntoUsers
                                               on new { SED.SubExtrasDetailID, SEDA.UserID }
                                           equals new { EPQU.SubExtrasDetailID, EPQU.UserID }
                                         join EX in db.ExtraPlanQuotas on EPQU.ExtraPlanQuotaID equals EX.ExtraPlanQuotaID
                                         where
                                           SEDA.UserID == id
                                         select new SubExtraDetailModel()
                                         {

                                             SubExtrasDetailID = (Int32)SEDA.SubExtrasDetailID,
                                             SubExtrasDetailName = SED.SubExtrasDetailName,
                                             SubExtrasDetailPrice = SED.SubExtrasDetailPrice,
                                             SubExtrasName = SE.SubExtrasName,
                                             SubExtrasSetupFee = EX.ExtraSetupCost,
                                             ExtraPlanQuotaValue = EX.ExtraPlanQuotaValue,
                                             ExtraPlanQuotaInterval = EX.ExtraPlanQuotaInterval,
                                         };

                model.listSummaryHardwareModel = from SEDA in db.SubHardwareDetailAssignToUsers
                                                 join SED in db.SubHardwaresDetails on SEDA.SubHardwaresDetailID equals SED.SubHardwareDetailID
                                                 join SE in db.SubHardwares on new { SubHardwareID = (Int32)SED.SubHardwareID } equals new { SubHardwareID = SE.SubHardwareID }
                                                 where
                                                  SEDA.UserID == id
                                                 select new SubHardwareDetailModel()
                                                 {

                                                     SubHardwareDetailID = (Int32)SEDA.SubHardwaresDetailID,
                                                     SubHardwareDetailName = SED.SubHardwareDetailName,
                                                     SubHardwareDetailPrice = SED.SubHardwareDetailPrice,
                                                     SubHardwareName = SE.SubHardwareName,
                                                     Quantity = SEDA.Quantity,
                                                     SubHardwareDetail = SE.SubHardwareDetail
                                                 };
            }

            return View("DetailOrders", model);
        }
        #endregion
        #region Common Functions
        public SelectListItem[] getOrderStatus()
        {
            return new[]
        {
          
           new SelectListItem { Value = "1", Text = "Payment Received" },
           new SelectListItem { Value = "2", Text = "Connection Connected" },
          
        };

        }

        public void SendMailAfterorderStatusChange(Int32? intOrderStatus, Int64 UserID)
        {
            if (intOrderStatus == 1)//Payment Received
            {
                //Get user Email by ID
                var getUserEmail = (from p in db.Users where p.ID == UserID select p.Email).SingleOrDefault();
                string message = "Your payment is received successfuly, your connection will be connected soon.";

                UserMailer.PaymentConfirmation(getUserEmail, "Payment Confirmation", message).Send();
            }
            else if (intOrderStatus == 2)//Connection Connected
            {
                //Get user Email by ID
                var getUserEmail = (from p in db.Users where p.ID == UserID select p.Email).SingleOrDefault();
                string message = "Your connection is connected successfully.";

                UserMailer.ConnectionConfirmation(getUserEmail, "Connection Confirmation", message).Send();
            }
        }
        #endregion

        #region[WHMCS--Save the data in WHMCS from Everynet]
        //public void InsertPlanNamesDetailIntoWHMCS(PlanNamesDetail model)
        //{
      

        //    // Instantiate the WebClient object
        //    WebClient WHMCSclient = new WebClient();

        //    #region Add Products in Database
        //    NameValueCollection formProducts = new NameValueCollection();
        //    formProducts.Add("username", Mainusername);
        //    formProducts.Add("password", Mainpassword);
        //    formProducts.Add("action", "addproduct");// action performed by the API:Functions

        //    formProducts.Add("type", "other");
        //    formProducts.Add("gid", "1");
        //    formProducts.Add("name", model.PlanDetailName);
        //    formProducts.Add("paytype", "recurring");

        //    formProducts.Add("pricing[1][monthly]", model.Price.ToString());
        //    Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formProducts);

        //    #endregion
        //}
        //public void InsertSubExtrasDetailsIntoWHMCS(SubExtrasDetail model)
        //{
      

        //    // Instantiate the WebClient object
        //    WebClient WHMCSclient = new WebClient();

        //    #region Add Products in Database
        //    NameValueCollection formProducts = new NameValueCollection();
        //    formProducts.Add("username", Mainusername);
        //    formProducts.Add("password", Mainpassword);
        //    formProducts.Add("action", "addproduct");// action performed by the API:Functions

        //    formProducts.Add("type", "other");
        //    formProducts.Add("gid", "4");
        //    formProducts.Add("name", model.SubExtrasDetailName);
        //    formProducts.Add("paytype", "recurring");

        //    formProducts.Add("pricing[1][monthly]", model.SubExtrasDetailPrice.ToString());
        //    Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formProducts);

        //    #endregion
        //}
        #endregion

        #region[WHMCS-Fetch the Data from WHMCS and Save in EveryNet]

        
        #region[Enums]
        public enum DefaultPlanID
        {
            defaultPlanID = 1
        }
        public enum DefaultExtraID
        {
            defaultExtraID = 1
        }

        String defautAggText = "<ul class='agree'><li>I am at least 18 years old.</li><li>I confirm that the information that I have given to everynet in this online application is correct.</li><li>I must retain my traditional landline telephone service, or I will lose my internet connection. If this happens I am liable for the reconnection fee and any cancellation fees for the service.</li><li>I am the telephone line account holder of the telephone line that will be used for this broadband service. In the alternative, I have permission from the current telephone line account holder to order this broadband service.</li><li>I am the account holder of the existing broadband service that will be transferred to Everynet.</li><li>Termination fees or other contractual obligations with my current provider may apply. These are my sole responsibility. My existing equipment may need to be returned to my current provider.</li><li>I understand that phone service should continue to work as normal during the transfer process.</li><li>I understand that there may be an outage of my internet service, making it unavailable for up to four hours on the date of transfer.</li><li>In the event that network conditions can no longer support the supply of this plan, Everynet reserves the right to change your plan to a plan with a lower cost and lower quota. If this occurs1</li></ul>";

        String checkExtraHere = "VOIP";
        String checkExtraHereT = "Telephone";
        String checkBundle = "Bundle";
        //String checkWifi = "Wifi";
        String checkWifi = "Router";
        String checkFilter= "Filter";
        //String checkHardware = "Hardware";
      
         public enum QuotaMonths
        {
            OneMonth = 1,
            ThreeMonth = 3,
            SubYearly = 6,
            Yearly = 12,
            BiYearly=24,
            TriYearly=36
        }

        public enum QuotaMonthYear
        {
            months,
            year
        }
        #endregion

        public static string Mainusername = ConfigurationManager.AppSettings["WhmcsUsername"].ToString();
        public static string Mainpassword = ConfigurationManager.AppSettings["WhmcsPassword"].ToString();
        public static string path = ConfigurationManager.AppSettings["WhmcsPath"].ToString();

        //make php file -getproductgroup
        public Int32 SaveDatainPlanNamesandSubExtras() //dbo.PlanNames, dbo.SubExtras, SubHardwares
        {
            //Note:
            //if -1 means WHMCS is currently not running, please run it first. 
            //if -2 means Some error occur while fetching data from Plans.
            try
            {
                #region[header]
                // Instantiate the WebClient object
                WebClient WHMCSclient = new WebClient();
                #endregion

                #region[Productgroup]
                string getXML = String.Empty;
                try
                {
                    NameValueCollection formcustom = new NameValueCollection();
                    formcustom.Add("username", Mainusername);
                    formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                    formcustom.Add("action", "getproductgroup");// action performed by the API:Functions
                    Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
                    getXML = Encoding.ASCII.GetString(responseDataContact);
                }
                catch
                {
                    return -1;
                }
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(getXML);


                XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);

                String getCommaSeparatedNames = String.Empty;
                String getCommaSeparatedIds = String.Empty;

                string queryname = "/whmcsapi/products/name";
                XmlNodeList xnListname = xd.SelectNodes(queryname, manager);
                foreach (XmlNode xnFname in xnListname)
                {
                    getCommaSeparatedNames += xnFname.InnerText + "||";
                }

                string queryid = "/whmcsapi/products/id";
                XmlNodeList xnListid = xd.SelectNodes(queryid, manager);
                foreach (XmlNode xnFid in xnListid)
                {
                    getCommaSeparatedIds += xnFid.InnerText + "||";
                }
                #endregion

                #region[Variables]
                string[] separator = new string[] { "||" };
                string[] strSplitArr = getCommaSeparatedNames.Split(separator, StringSplitOptions.None);
                string[] strSplitArrId = getCommaSeparatedIds.Split(separator, StringSplitOptions.None);
                #endregion

                #region[for Loop]
                for (int i = 0; i < strSplitArrId.Length; i++)
                {
                    if (!String.IsNullOrEmpty(strSplitArrId[i]))
                    {
                        string getname = strSplitArr[i].ToString();
                        Int32 getId = Convert.ToInt32(strSplitArrId[i].ToString());

                        PlanModel model = new PlanModel();
                        //check planname already exists in database or not

                        string checkExtra = checkExtraHere.ToUpper();
                        string checkExtraT = checkExtraHereT.ToUpper();
                        string chkBundle = checkBundle.ToUpper();
                        
                        //string chkHardware = checkHardware.ToUpper();
                       
                        string chkWifi= checkWifi.ToUpper();
                        string chkFilter = checkFilter.ToUpper();

                        string Upgetname = getname.ToUpper();
                        //Extras(not bundle and hardware)
                        if ((Upgetname.Contains(checkExtra) && !Upgetname.Contains(chkBundle) && !Upgetname.Contains(chkWifi) && !Upgetname.Contains(chkFilter)) || (Upgetname.Contains(checkExtraT) && !Upgetname.Contains(chkBundle) && !Upgetname.Contains(chkWifi) && !Upgetname.Contains(chkFilter))) // Insert into extras Tables.
                        {
                           
                            var chkPlanNameExtras = (from p in db.SubExtras where p.SubExtrasID == getId select p.SubExtrasID).FirstOrDefault();
                            if (chkPlanNameExtras == 0)
                            {
                                SubExtra modelSub = new SubExtra();
                                modelSub.SubExtrasID = getId;
                                modelSub.SubExtrasName = getname;
                                modelSub.SubExtrasDetail = "";
                                modelSub.SubExtrasPrice = 0;
                                modelSub.ExtrasID = (int)DefaultExtraID.defaultExtraID;
                                modelSub.Agreement = defautAggText;
                                db.AddToSubExtras(modelSub);
                                
                            }
                        }
                        //Extras(if hardware)
                        else if ((Upgetname.Contains(chkWifi) || Upgetname.Contains(chkFilter)) && !Upgetname.Contains(chkBundle)) // Insert into SubHardware Tables.
                        {
                            var chkPlanNameExtrasHardware = (from p in db.SubHardwares where p.SubHardwareID == getId select p.SubHardwareID).FirstOrDefault();
                            if (chkPlanNameExtrasHardware == 0)
                            {
                                SubHardware modelSubHardware = new SubHardware();
                                modelSubHardware.SubHardwareID = getId;
                                modelSubHardware.SubHardwareName = getname;
                                modelSubHardware.SubHardwareDetail = "";
                                modelSubHardware.SubHardwarePrice = 0;
                                modelSubHardware.HardwareID = (int)DefaultExtraID.defaultExtraID;
                                modelSubHardware.Agreement = defautAggText;
                                db.AddToSubHardwares(modelSubHardware);

                            }
                        }
                        else  //Insert into Simple Tables.(Plan Names)
                        {
                            var chkPlanName = (from p in db.PlanNames where p.ID == getId select p.ID).FirstOrDefault();
                            if (chkPlanName == 0)
                            {
                                PlanName modelplan = new PlanName();
                                modelplan.ID = getId;
                                modelplan.Name = getname;
                                modelplan.PlanID = (int)DefaultPlanID.defaultPlanID;
                                modelplan.RedirectUrl = "signup";
                                modelplan.Agreement = defautAggText;
                                db.AddToPlanNames(modelplan);
                                
                            }
                        }

                    }
                }
                db.SaveChanges();
                #endregion

                return 0;
            }
            catch
            {
                return -2;
            }
        }

        //use inbuilt function-getproducts
        public Int32 SaveDatainPlanNameDetailandSubExtraDetail() //dbo.PlanNamesDetail, dbo.SubExtrasDetails, SubHardwaresDetails
        {
            //Note:
            //if -1 means WHMCS is currently not running, please run it first. 
            //if -2 means Some error occur while fetching data from PlansDetail.
            try
            {
                #region[header]
                // Instantiate the WebClient object
                WebClient WHMCSclient = new WebClient();
                #endregion

                #region[Products]
                string getXML = String.Empty;
                try
                {
                    NameValueCollection formcustom = new NameValueCollection();
                    formcustom.Add("username", Mainusername);
                    formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                    formcustom.Add("action", "getproducts");// action performed by the API:Functions
                    Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
                    getXML = Encoding.ASCII.GetString(responseDataContact);
                }
                catch
                {
                    return -1;
                }
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(getXML);
                XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);

                String getCommaSeparatedPID = String.Empty;
                String getCommaSeparatedGID = String.Empty;
                String getCommaSeparatedName = String.Empty;

                string queryPID = "/whmcsapi/products/product/pid";
                XmlNodeList xnListPID = xd.SelectNodes(queryPID, manager);
                foreach (XmlNode xnPID in xnListPID)
                {
                    getCommaSeparatedPID += xnPID.InnerText + "||";
                }

                string queryGID = "/whmcsapi/products/product/gid";
                XmlNodeList xnListGID = xd.SelectNodes(queryGID, manager);
                foreach (XmlNode xnGid in xnListGID)
                {
                    getCommaSeparatedGID += xnGid.InnerText + "||";
                }

                string queryName = "/whmcsapi/products/product/name";
                XmlNodeList xnListName = xd.SelectNodes(queryName, manager);
                foreach (XmlNode xnName in xnListName)
                {
                    getCommaSeparatedName += xnName.InnerText + "||";
                }
                #endregion

                #region[Variables]
                string[] separator = new string[] { "||" };
                string[] strSplitArrPID = getCommaSeparatedPID.Split(separator, StringSplitOptions.None);
                string[] strSplitArrGID = getCommaSeparatedGID.Split(separator, StringSplitOptions.None);
                string[] strSplitArrName = getCommaSeparatedName.Split(separator, StringSplitOptions.None);
                #endregion

                #region[for loop]

                for (int i = 0; i < strSplitArrPID.Length; i++)
                {
                    if (!String.IsNullOrEmpty(strSplitArrPID[i]))
                    {

                        Int32 getPID = Convert.ToInt32(strSplitArrPID[i].ToString());
                        string getname = strSplitArrName[i].ToString();
                        Int32 getGID = Convert.ToInt32(strSplitArrGID[i].ToString());


                        //check planname already exists in database or not
                        string checkExtra = checkExtraHere.ToUpper();
                        string checkExtraT = checkExtraHereT.ToUpper();
                        string chkBundle = checkBundle.ToUpper();

                        //string chkHardware = checkHardware.ToUpper();

                        string chkWifi = checkWifi.ToUpper();
                        string chkFilter = checkFilter.ToUpper();

                        string Upgetname = getname.ToUpper();
                        //Extras
                        if ((Upgetname.Contains(checkExtra) && !Upgetname.Contains(chkBundle) && !Upgetname.Contains(chkWifi) && !Upgetname.Contains(chkFilter)) || (Upgetname.Contains(checkExtraT) && !Upgetname.Contains(chkBundle) && !Upgetname.Contains(chkWifi) && !Upgetname.Contains(chkFilter))) // Insert into extras Tables.
                       
                        {

                            var chkerr = (from p in db.SubExtras where p.SubExtrasID == getGID select p.SubExtrasID).FirstOrDefault();
                            if (chkerr > 0)
                            {
                                var chkPID = (from p in db.SubExtrasDetails where p.SubExtrasDetailID == getPID select p.SubExtrasDetailID).FirstOrDefault();
                                if (chkPID == 0)
                                {

                                    SubExtrasDetail modelS = new SubExtrasDetail
                                   {
                                       SubExtrasDetailID = getPID,
                                       SubExtrasDetailName = getname,
                                       SubExtrasDetailPrice = 0,
                                       SubExtrasID = getGID
                                   };
                                    db.AddToSubExtrasDetails(modelS);
                                    


                                }
                            }
                        }

                        else if ((Upgetname.Contains(chkWifi) || Upgetname.Contains(chkFilter)) && !Upgetname.Contains(chkBundle)) // Insert into SubHardwareDetail Tables.
                        {
                            var chkerr = (from p in db.SubHardwares where p.SubHardwareID == getGID select p.SubHardwareID).FirstOrDefault();
                            if (chkerr > 0)
                            {
                                var chkPID = (from p in db.SubHardwaresDetails where p.SubHardwareDetailID == getPID select p.SubHardwareDetailID).FirstOrDefault();
                                if (chkPID == 0)
                                {

                                    SubHardwaresDetail modelS = new SubHardwaresDetail
                                    {
                                        SubHardwareDetailID = getPID,
                                        SubHardwareDetailName = getname,
                                        SubHardwareDetailPrice = 0,
                                        SubHardwareID = getGID
                                    };
                                    db.AddToSubHardwaresDetails(modelS);



                                }
                            }
                        }
                        else  //Insert into Simple Tables.(PlanNameDetail)
                        {

                            var chkerr = (from p in db.PlanNames where p.ID == getGID select p.ID).FirstOrDefault();
                            if (chkerr > 0)
                            {
                                var chkPID1 = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == getPID select p.PlanNamesDetailID).FirstOrDefault();
                                if (chkPID1 == 0)
                                {
                                    PlanNamesDetail modelP = new PlanNamesDetail
                                   {
                                       PlanNamesDetailID = getPID,
                                       PlanDetailName = getname,
                                       Price = 0,
                                       PlanNamesID = getGID,
                                       PlanDetailQuota = "0"
                                   };
                                    db.AddToPlanNamesDetails(modelP);



                                }
                            }
                        }

                    }
                }
                db.SaveChanges();

                #endregion
                return 0;
            }
            catch
            {
                return -2;
            }

        }

        //make php file -getpricing
        public Int32 SaveDatainPlanExtraForPrice() //dbo.PlanNamesDetail, dbo.SubExtrasDetails
        {
            //Note:
            //if -1 means WHMCS is currently not running, please run it first. 
            //if -2 means Some error occur while fetching data from Price.
            try
            {
                #region[header]
                // Instantiate the WebClient object
                WebClient WHMCSclient = new WebClient();
                #endregion

                #region[Price]
                string getXML = String.Empty;
                try
                {
                NameValueCollection formcustom = new NameValueCollection();
                formcustom.Add("username", Mainusername);
                formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formcustom.Add("action", "getpricing");// action performed by the API:Functions
                Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
                getXML = Encoding.ASCII.GetString(responseDataContact);
                }
                catch
                {
                    return -1;
                }
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(getXML);
                XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);

                String getCommaSeparatedRelID = String.Empty;
                String getCommaSeparatedMonthly = String.Empty;
                String getCommaSeparatedType = String.Empty;
                String getCommaSeparatedCurrency = String.Empty;

                string queryRelID = "/whmcsapi/products/relid";
                XmlNodeList xnListRelID = xd.SelectNodes(queryRelID, manager);
                foreach (XmlNode xnRelID in xnListRelID)
                {
                    getCommaSeparatedRelID += xnRelID.InnerText + "||";
                }

                string queryMonthly = "/whmcsapi/products/monthly";
                XmlNodeList xnListMonthly = xd.SelectNodes(queryMonthly, manager);
                foreach (XmlNode xnMonthly in xnListMonthly)
                {
                    getCommaSeparatedMonthly += xnMonthly.InnerText + "||";
                }

                string queryType = "/whmcsapi/products/type";
                XmlNodeList xnListType = xd.SelectNodes(queryType, manager);
                foreach (XmlNode xnType in xnListType)
                {
                    getCommaSeparatedType += xnType.InnerText + "||";
                }

                string queryCurrency = "/whmcsapi/products/currency";
                XmlNodeList xnListCurrency = xd.SelectNodes(queryCurrency, manager);
                foreach (XmlNode xnCurrency in xnListCurrency)
                {
                    getCommaSeparatedCurrency += xnCurrency.InnerText + "||";
                }
                #endregion

                #region[Variables]
                string[] separator = new string[] { "||" };
                string[] strSplitArrRelID = getCommaSeparatedRelID.Split(separator, StringSplitOptions.None);
                string[] strSplitArrMonthly = getCommaSeparatedMonthly.Split(separator, StringSplitOptions.None);
                string[] strSplitArrType = getCommaSeparatedType.Split(separator, StringSplitOptions.None);
                string[] strSplitArrCurrency = getCommaSeparatedCurrency.Split(separator, StringSplitOptions.None);
                #endregion

                #region[for loop]
                for (int i = 0; i < strSplitArrRelID.Length; i++)
                {

                    if (strSplitArrType[i] == "product" && strSplitArrCurrency[i] == "1")
                    {

                        if (!String.IsNullOrEmpty(strSplitArrRelID[i]))
                        {
                            Int32 planNDID = Convert.ToInt32(strSplitArrRelID[i]);
                            //check Is it extas or not
                            var chkExits = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == planNDID select p.PlanNamesDetailID).FirstOrDefault();
                            var chkExitsH = (from p in db.SubHardwaresDetails where p.SubHardwareDetailID == planNDID select p.SubHardwareDetailID).FirstOrDefault();
                            if (chkExits > 0) //Update Values in PlanNamesDetail
                            {
                                //update price in PlanNamesDetail table in the database.

                                PlanNamesDetail dbPlanNamesDetail = new PlanNamesDetail { PlanNamesDetailID = chkExits };
                                db.PlanNamesDetails.Attach(dbPlanNamesDetail);
                                db.PlanNamesDetails.ApplyCurrentValues(dbPlanNamesDetail);
                                dbPlanNamesDetail.Price = Convert.ToDecimal(strSplitArrMonthly[i]);
                                db.SaveChanges(); 

                            }
                            else if (chkExitsH > 0)
                            {
                                //update price in SubHardwareDetail table in the database.

                                SubHardwaresDetail dbPlanNamesDetailH = new SubHardwaresDetail { SubHardwareDetailID = chkExitsH };
                                db.SubHardwaresDetails.Attach(dbPlanNamesDetailH);
                                db.SubHardwaresDetails.ApplyCurrentValues(dbPlanNamesDetailH);
                                dbPlanNamesDetailH.SubHardwareDetailPrice = Convert.ToDecimal(strSplitArrMonthly[i]);
                                db.SaveChanges(); 
                            }
                            else //Update Values in SubExtrasDetails
                            {
                                Int32 planNDI = Convert.ToInt32(strSplitArrRelID[i]);
                                var chkExitsD = (from p in db.SubExtrasDetails where p.SubExtrasDetailID == planNDI select p.SubExtrasDetailID).FirstOrDefault();
                                if (chkExitsD > 0)
                                {
                                    //update price in the database.
                                    SubExtrasDetail dbSubExtrasDetails = new SubExtrasDetail { SubExtrasDetailID = chkExitsD };
                                    db.SubExtrasDetails.Attach(dbSubExtrasDetails);
                                    db.SubExtrasDetails.ApplyCurrentValues(dbSubExtrasDetails);
                                    dbSubExtrasDetails.SubExtrasDetailPrice = Convert.ToDecimal(strSplitArrMonthly[i]);
                                    db.SaveChanges(); 

                                }

                            }
                        }
                    }
                }
               
                #endregion
                return 0;
            }
            catch
            {
                return -2;
            }
        }

        //make php file -getproductconfiglinks, getpriceforQuota, getGidbyPid
        public void CommonQuotas(Int32 Qmonth, string QmonthName, decimal ArrMy, int? GIDbyPID)
       {
           PlanQuota modelM = new PlanQuota();
           modelM.PlanQuotaValue = Qmonth;
           modelM.PlanQuotaInterval = QmonthName;
           modelM.SetupCost = ArrMy;
           modelM.PlanNamesID = GIDbyPID;
           db.AddToPlanQuotas(modelM);
           db.SaveChanges();
       }
        public void CommonQuotasExtra(Int32 Qmonth, string QmonthName, decimal ArrMy, int GIDbyPID)
        {
            ExtraPlanQuota modelM = new ExtraPlanQuota();
            modelM.ExtraPlanQuotaValue = Qmonth;
            modelM.ExtraPlanQuotaInterval = QmonthName;
            modelM.ExtraSetupCost = ArrMy;
            modelM.SubExtrasID = GIDbyPID;
            db.AddToExtraPlanQuotas(modelM);
            db.SaveChanges();
        }
        public Int32 SaveQuotaInDatabase() //PlanQuota //ExtraPlanQuota
        {
            //Note:
            //if -1 means WHMCS is currently not running, please run it first. 
            //if -2 means Some error occur while fetching data from Quota.
            try
            {
                #region[header]
                // Instantiate the WebClient object
                WebClient WHMCSclient = new WebClient();
                #endregion

                #region[//1. ProductConfig]
                string getXML = String.Empty;
                try
                {
                    NameValueCollection formcustom = new NameValueCollection();
                    formcustom.Add("username", Mainusername);
                    formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                    formcustom.Add("action", "getproductconfiglinks");// action performed by the API:Functions
                    Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
                    getXML = Encoding.ASCII.GetString(responseDataContact);
                }
                catch
                {
                    return -1;
                }
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(getXML);
                XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);

                String getCommaSeparatedGID = String.Empty;
                String getCommaSeparatedPID = String.Empty;

                string queryGID = "/whmcsapi/products/gid";
                XmlNodeList xnListGID = xd.SelectNodes(queryGID, manager);
                foreach (XmlNode xnGID in xnListGID)
                {
                    getCommaSeparatedGID += xnGID.InnerText + "||";
                }

                string queryPID = "/whmcsapi/products/pid";
                XmlNodeList xnListPID = xd.SelectNodes(queryPID, manager);
                foreach (XmlNode xnPID in xnListPID)
                {
                    getCommaSeparatedPID += xnPID.InnerText + "||";
                }
                #endregion

                #region[//2.Quota Price]
                NameValueCollection formcustomP = new NameValueCollection();
                formcustomP.Add("username", Mainusername);
                formcustomP.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formcustomP.Add("action", "getpriceforQuota");// action performed by the API:Functions
                Byte[] responseDataContactP = WHMCSclient.UploadValues(path, formcustomP);
                string getXMLP = Encoding.ASCII.GetString(responseDataContactP);


                XmlDocument xdP = new XmlDocument();
                xdP.LoadXml(getXMLP);
                XmlNamespaceManager managerP = new XmlNamespaceManager(xdP.NameTable);

                String getCommaSeparatedrelId = String.Empty;
                String getCommaSeparatedType = String.Empty;
                String getCommaSeparatedMsetupfee = String.Empty;
                String getCommaSeparatedQsetupfee = String.Empty;
                String getCommaSeparatedSsetupfee = String.Empty;

                String getCommaSeparatedAsetupfee = String.Empty;
                String getCommaSeparatedBsetupfee = String.Empty;
                String getCommaSeparatedTsetupfee = String.Empty;

                string queryrel = "/whmcsapi/products/relid";
                XmlNodeList xnListrel = xdP.SelectNodes(queryrel, managerP);
                foreach (XmlNode xnrel in xnListrel)
                {
                    getCommaSeparatedrelId += xnrel.InnerText + "||";
                }

                string querytype = "/whmcsapi/products/type";
                XmlNodeList xnListtype = xdP.SelectNodes(querytype, managerP);
                foreach (XmlNode xntype in xnListtype)
                {
                    getCommaSeparatedType += xntype.InnerText + "||";
                }

                string queryMsetupfee = "/whmcsapi/products/msetupfee";
                XmlNodeList xnListM = xdP.SelectNodes(queryMsetupfee, managerP);
                foreach (XmlNode xnM in xnListM)
                {
                    getCommaSeparatedMsetupfee += xnM.InnerText + "||";
                }

                string queryQsetupfee = "/whmcsapi/products/qsetupfee";
                XmlNodeList xnListQ = xdP.SelectNodes(queryQsetupfee, managerP);
                foreach (XmlNode xnQ in xnListQ)
                {
                    getCommaSeparatedQsetupfee += xnQ.InnerText + "||";
                }

                string querySsetupfee = "/whmcsapi/products/ssetupfee";
                XmlNodeList xnListS = xdP.SelectNodes(querySsetupfee, managerP);
                foreach (XmlNode xnS in xnListS)
                {
                    getCommaSeparatedSsetupfee += xnS.InnerText + "||";
                }

                string queryAsetupfee = "/whmcsapi/products/asetupfee";
                XmlNodeList xnListA = xdP.SelectNodes(queryAsetupfee, managerP);
                foreach (XmlNode xnA in xnListA)
                {
                    getCommaSeparatedAsetupfee += xnA.InnerText + "||";
                }

                string queryBsetupfee = "/whmcsapi/products/bsetupfee";
                XmlNodeList xnListB = xdP.SelectNodes(queryBsetupfee, managerP);
                foreach (XmlNode xnB in xnListB)
                {
                    getCommaSeparatedBsetupfee += xnB.InnerText + "||";
                }

                string queryTsetupfee = "/whmcsapi/products/tsetupfee";
                XmlNodeList xnListT = xdP.SelectNodes(queryTsetupfee, managerP);
                foreach (XmlNode xnT in xnListT)
                {
                    getCommaSeparatedTsetupfee += xnT.InnerText + "||";
                }
                #endregion

                #region[//3.GetGidbyPid]
                NameValueCollection formcustomG = new NameValueCollection();
                formcustomG.Add("username", Mainusername);
                formcustomG.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formcustomG.Add("action", "getGidbyPid");// action performed by the API:Functions
                Byte[] responseDataContactG = WHMCSclient.UploadValues(path, formcustomG);
                string getXMLG = Encoding.ASCII.GetString(responseDataContactG);

                XmlDocument xdG = new XmlDocument();
                xdG.LoadXml(getXMLG);
                XmlNamespaceManager managerG = new XmlNamespaceManager(xdG.NameTable);

                String getCommaSeparatedGGID = String.Empty;
                String getCommaSeparatedGPID = String.Empty;

                string queryG = "/whmcsapi/products/gid";
                XmlNodeList xnListG = xdG.SelectNodes(queryG, managerG);
                foreach (XmlNode xnG in xnListG)
                {
                    getCommaSeparatedGGID += xnG.InnerText + "||";
                }

                string queryP = "/whmcsapi/products/id";
                XmlNodeList xnListP = xdG.SelectNodes(queryP, managerG);
                foreach (XmlNode xnP in xnListP)
                {
                    getCommaSeparatedGPID += xnP.InnerText + "||";
                }
                #endregion

                #region[Variables]
                string[] separator = new string[] { "||" };
                string[] strSplitArrGID = getCommaSeparatedGID.Split(separator, StringSplitOptions.None);
                string[] strSplitArrPID = getCommaSeparatedPID.Split(separator, StringSplitOptions.None);

                string[] strSplitArrrelID = getCommaSeparatedrelId.Split(separator, StringSplitOptions.None);
                string[] strSplitArrType = getCommaSeparatedType.Split(separator, StringSplitOptions.None);
                string[] strSplitArrM = getCommaSeparatedMsetupfee.Split(separator, StringSplitOptions.None);
                string[] strSplitArrQ = getCommaSeparatedQsetupfee.Split(separator, StringSplitOptions.None);
                string[] strSplitArrS = getCommaSeparatedSsetupfee.Split(separator, StringSplitOptions.None);

                string[] strSplitArrA = getCommaSeparatedAsetupfee.Split(separator, StringSplitOptions.None);
                string[] strSplitArrB = getCommaSeparatedBsetupfee.Split(separator, StringSplitOptions.None);
                string[] strSplitArrT = getCommaSeparatedTsetupfee.Split(separator, StringSplitOptions.None);

                string[] strSplitArrGGID = getCommaSeparatedGGID.Split(separator, StringSplitOptions.None);
                string[] strSplitArrGPID = getCommaSeparatedGPID.Split(separator, StringSplitOptions.None);
                #endregion

                #region[for loop]
                for (int i = 0; i < strSplitArrGID.Length; i++)
                {
                    if (!String.IsNullOrEmpty(strSplitArrPID[i]))
                    {
                        Int32 GID = Convert.ToInt32(strSplitArrGID[i]);
                        Int32 PID = Convert.ToInt32(strSplitArrPID[i]);

                        //check PID is Extras or NOT
                        var chkPID = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == PID select p.PlanNamesDetailID).FirstOrDefault();
                        #region[Quotas]
                        if (chkPID > 0) //Plan Name Detail
                        {
                            //for each loop for Quota Price 
                            for (int j = 0; j < strSplitArrrelID.Length; j++)
                            {
                                if (strSplitArrType[j] == "configoptions" && GID == Convert.ToInt32(strSplitArrrelID[j]))
                                {
                                    //Insert into PlanQuota
                                    //Run all the If conditions:
                                    //monthly
                                    decimal ArrM = Convert.ToDecimal(strSplitArrM[j]);
                                    decimal ArrQ = Convert.ToDecimal(strSplitArrQ[j]);
                                    decimal ArrS = Convert.ToDecimal(strSplitArrS[j]);

                                    decimal ArrA = Convert.ToDecimal(strSplitArrA[j]);
                                    decimal ArrB = Convert.ToDecimal(strSplitArrB[j]);
                                    decimal ArrT = Convert.ToDecimal(strSplitArrT[j]);

                                    Int32 getGIDbyPID = 0;
                                    //get the GroupId of ProductID
                                    for (int l = 0; l < strSplitArrGPID.Length; l++)
                                    {
                                        if (!String.IsNullOrEmpty(strSplitArrGPID[l]))
                                        {
                                            if (PID == Convert.ToInt32(strSplitArrGPID[l]))
                                            {
                                                getGIDbyPID = Convert.ToInt32(strSplitArrGGID[l]);
                                            }
                                        }
                                    }
                                    //monthly
                                    if (ArrM > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.OneMonth;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrM[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {
                                             CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                        }
                                    }
                                    //quateraly
                                    if (ArrQ > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.ThreeMonth;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrQ[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {
                                            CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                           
                                        }
                                    }
                                    //semifinally
                                    if (ArrS > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.SubYearly;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrS[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {
                                            CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                        }
                                    }

                                    //Annual
                                    if (ArrA > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.Yearly;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrA[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {

                                            CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                        }
                                    }
                                    //BiAnnual
                                    if (ArrB > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.BiYearly;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrB[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {

                                            CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                        }
                                    }
                                    //TriAnnual
                                    if (ArrT > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.TriYearly;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrT[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {

                                            CommonQuotas(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                        }
                                    }

                                }

                            }

                        }
                        #endregion
                        #region[Extra Quotas]
                        else //Extras
                        {
                            var chkExitsD = (from p in db.SubExtrasDetails where p.SubExtrasDetailID == PID select p.SubExtrasDetailID).FirstOrDefault();
                            if (chkExitsD > 0) //Plan Name Detail
                            {
                                //for each loop for Quota Price 
                                for (int j = 0; j < strSplitArrrelID.Length; j++)
                                {
                                    if (strSplitArrType[j] == "configoptions" && GID == Convert.ToInt32(strSplitArrrelID[j]))
                                    {
                                        //Insert into PlanQuota
                                        //Run all the If conditions:
                                        //monthly
                                        decimal ArrM = Convert.ToDecimal(strSplitArrM[j]);
                                        decimal ArrQ = Convert.ToDecimal(strSplitArrQ[j]);
                                        decimal ArrS = Convert.ToDecimal(strSplitArrS[j]);

                                        decimal ArrA = Convert.ToDecimal(strSplitArrA[j]);
                                        decimal ArrB = Convert.ToDecimal(strSplitArrB[j]);
                                        decimal ArrT = Convert.ToDecimal(strSplitArrT[j]);

                                        Int32 getGIDbyPID = 0;
                                        //get the GroupId of ProductID
                                        for (int l = 0; l < strSplitArrGPID.Length; l++)
                                        {
                                            if (!String.IsNullOrEmpty(strSplitArrGPID[l]))
                                            {
                                                if (PID == Convert.ToInt32(strSplitArrGPID[l]))
                                                {
                                                    getGIDbyPID = Convert.ToInt32(strSplitArrGGID[l]);
                                                }
                                            }
                                        }

                                        if (ArrM > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.OneMonth;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrM[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                               
                                                CommonQuotasExtra(Qmonth,QmonthName,ArrMy,GIDbyPID);
                                            }
                                        }
                                        //quateraly
                                        if (ArrQ > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.ThreeMonth;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrQ[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {

                                                CommonQuotasExtra(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                            }
                                        }
                                        //semifinally
                                        if (ArrS > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.SubYearly;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrS[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                CommonQuotasExtra(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                            }
                                        }

                                        //Annual
                                        if (ArrA > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.Yearly;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrA[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                CommonQuotasExtra(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                            }
                                        }
                                        //BiAnnual
                                        if (ArrB > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.BiYearly;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrB[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                CommonQuotasExtra(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                            }
                                        }
                                        //TriAnnual
                                        if (ArrT > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.TriYearly;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrT[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                CommonQuotasExtra(Qmonth, QmonthName, ArrMy, GIDbyPID);
                                            }
                                        }
                                    }

                                }
                            }
                        }
                        #endregion
                    }
                }

                #endregion
                return 0;
            }
            catch
            {
                return -2;
            }
        }

       /* public Int32 GetTotalCountOfWHMCSProductFGroups()
        {
            Int32 Totalcount = 0;

            #region[header]
            // Instantiate the WebClient object
            WebClient WHMCSclient = new WebClient();
            #endregion

            #region[Productgroup]
            string getXML = String.Empty;
            try
            {
                NameValueCollection formcustom = new NameValueCollection();
                formcustom.Add("username", Mainusername);
                formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formcustom.Add("action", "getproductgroupcount");// action performed by the API:Functions
                Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
                getXML = Encoding.ASCII.GetString(responseDataContact);
            }
            catch
            {
                return -1;
            }

            XmlDocument xd = new XmlDocument();
            xd.LoadXml(getXML);
            
            XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);
            String getCommaSeparatedCount = String.Empty;
            String queryCount = "/whmcsapi/products/count";
            XmlNodeList xnListcount = xd.SelectNodes(queryCount, manager);
            foreach (XmlNode xnCount in xnListcount)
            {
                getCommaSeparatedCount = xnCount.InnerText;
            }
            if (!String.IsNullOrEmpty(getCommaSeparatedCount))
            {
                Totalcount = Convert.ToInt32(getCommaSeparatedCount);
            }

            #endregion

            return Totalcount;
        }*/

        public ActionResult GetDatafromWHMCSPlans()
        {
            WHMCS model = new WHMCS();
            model.returnResut = "";
            /*Int32 WHMCSGroupcount = GetTotalCountOfWHMCSProductFGroups();
            if (WHMCSGroupcount == 0)
            {
                model.returnResut = "There is no Product Group in WHMCS.";
            }
            else if (WHMCSGroupcount > 0)
            { 
              var sqlCount = (from p in db.PlanNames select p.ID).Count();
              var sqlCountSub = (from ps in db.SubExtras select ps.SubExtrasID).Count();

              if (WHMCSGroupcount == sqlCount + sqlCountSub)
              {
                  model.returnResut = "Product Group is updated with WHMCS.";
              }
              else
              {
                  model.returnResut = "Product Group is not updated with WHMCS.";
              }
            }*/
            
            return View("GetDatafromWHMCSPlans",model);
        }

        public ActionResult GetDatafromWHMCSPlansReal()
        {
            string errText = "<span style='color:Red'>WHMCS is currently not running, please run it first.</span>";
            string errText2 = "<span style='color:Red'>Some error occur while fetching data from</span>";
            WHMCS model = new WHMCS();
            model.returnResut = "<span style='color:Green'>Plans are Successfully updated with WHMCS.</span>";

            //PlanName and SubExtra
            #region[level1]
            Int32 getvalue = SaveDatainPlanNamesandSubExtras();
            if (getvalue == -1)
            {
                model.returnResut = errText;
            }
            else if (getvalue == -2)
            {
                model.returnResut = errText2 + " <span style='color:Red'>Plans.</span>";
            }
            #endregion
            #region[level2]
            else if (getvalue == 0) //1st level Success, 2nd Level Start
            {
                //PlanNameDetail and SubExtraDetail

                Int32 getvalue2 = SaveDatainPlanNameDetailandSubExtraDetail();
                if (getvalue2 == -1)
                {
                    model.returnResut = errText;
                }
                else if (getvalue2 == -2)
                {
                    model.returnResut = errText2 + " <span style='color:Red'>Plan details.</span>";
                }
            #endregion


            }

            return View("GetDatafromWHMCSPlans", model);
        }

        public ActionResult GetDatafromWHMCSQuota()
        {
            WHMCS model = new WHMCS();
            model.returnResut = "";
            return View("GetDatafromWHMCSQuota",model);
        }

        public ActionResult GetDatafromWHMCSQuotaReal()
        {
            string errText = "<span style='color:Red'>WHMCS is currently not running, please run it first.</span>";
            string errText2 = "<span style='color:Red'>Some error occur while fetching data from</span>";
            WHMCS model = new WHMCS();
            model.returnResut = "<span style='color:Green'>Quotas are Successfully updated with WHMCS.</span>";

            // //Plan Quota and Extra Plan Quota
            Int32 getvalue4 = SaveQuotaInDatabase();
            if (getvalue4 == -1)
            {
                model.returnResut = errText;
            }
            else if (getvalue4 == -2)
            {
                model.returnResut = errText2 + " <span style='color:Red'>Quota.</span>";
            }
            else if (getvalue4 == 0) //All Levels Completed.
            {
                //default message show.
            }
            return View("GetDatafromWHMCSQuota", model);
        }

        public ActionResult GetDatafromWHMCSPrice()
        {
            WHMCS model = new WHMCS();
            model.returnResut = "";
            return View("GetDatafromWHMCSPrice",model);
        }

        public ActionResult GetDatafromWHMCSPriceReal()
        {
            string errText = "<span style='color:Red'>WHMCS is currently not running, please run it first.</span>";
            string errText2 = "<span style='color:Red'>Some error occur while fetching data from</span>";
            WHMCS model = new WHMCS();
            model.returnResut = "<span style='color:Green'>Price is Successfully updated with WHMCS.</span>";


            //Pricing
            Int32 getvalue3 = SaveDatainPlanExtraForPrice();
            if (getvalue3 == -1)
            {
                model.returnResut = errText;
            }
            else if (getvalue3 == -2)
            {
                model.returnResut = errText2 + " <span style='color:Red'>Price.</span>";
            }
            else if (getvalue3 == 0) //3rd level Success, 4th Level Start
            {

            }
            return View("GetDatafromWHMCSPrice", model);
        }
        #endregion

    }

}
